import CryptoJS from 'crypto-js';
import { CRYPTO_WEB_KEY } from '@/constants/config';

// 密钥
const secretKey = CRYPTO_WEB_KEY;

class CryptoCache {
	// 存储方式
	local: Storage;
	// 是否加密
	encrypt: Boolean;

	constructor(local: Storage, encrypt: Boolean) {
		this.local = local;
		this.encrypt = encrypt;
	}

	// 存储到本地的数据
	setItem(key: string, value: any) {
		// 加密 value
		const encryptedValue = this.encrypt ? CryptoJS.AES.encrypt(value, secretKey).toString() : value;
		// 存入本地
		this.local.setItem(key, JSON.stringify(encryptedValue));
	}
	// 获取存储的数据
	getItem(key: string) {
		// 解密 value
		const decryptValue = this.local.getItem(key);
		// 本地无存储
		if (!decryptValue) return null;
		// 取出本地存储
		return this.encrypt
			? CryptoJS.AES.decrypt(JSON.parse(decryptValue), secretKey).toString(CryptoJS.enc.Utf8)
			: JSON.parse(decryptValue);
	}
	// 删除本地数据
	removeItem(key: string) {
		this.local.removeItem(key);
	}
	// 删除本地所有数据
	clearItem() {
		this.local.clear();
	}
}

// sessionStorage 加密
const sessionCryptoCache = new CryptoCache(sessionStorage, true);
// sessionStorage 不加密
const sessionNoCryptoCache = new CryptoCache(sessionStorage, false);
// localStorage 加密
const localCryptoCache = new CryptoCache(localStorage, true);
// localStorage 不加密
const localNoCryptoCache = new CryptoCache(localStorage, false);

export { sessionCryptoCache, sessionNoCryptoCache, localCryptoCache, localNoCryptoCache };
